import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Layout from '../alyout/Layout'
import User from '../views/user/User.vue'
import Workbench from '../views/work/Workbench.vue'
// import Management from '../views/management/Management.vue'
import Newvisit from '../views/newvisit/Newvisit.vue'
import Register from '../views/register/Register.vue'
import Drug from '../views/drug/Drug.vue'
// import Charge from '../views/charge/Charge.vue'
// import Patient from '../views/patient/Patient.vue'
// import Drugmanagement from '../views/drugmanagement/Drugmanagement.vue'
import Member from '../views/member/Member.vue'
import Statistics from '../views/statistics/Statistics.vue'
import Case from '../views/case/Case.vue'

// 登录界面相关引入
import Login from '../views/login/Login.vue';
import LoginPart from '../views/login/components/LoginPart.vue'
import RegistPart from '../views/login/components/RegistPart.vue'
// import FindPwd from '../views/login/components/FindPwd.vue'
import Apply from '../views/login/components/Apply.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout/user'
  },
  {
    path: '/login',
    component: Login,
    children: [
      {
        path: 'login',
        component: LoginPart
      },
      {
        path: "regist",
        component: RegistPart
      },
      {
        path: 'apply',
        component: Apply
      }
    ]
  },
  {
    path: '/layout',
    name: 'layout',
    component: Layout,
    children: [
      {
        path: 'user',
        name: 'user',
        component: User,
        meta: {
          title: "经营概况",
          imgIndex: 0
        }
      },
      {
        path: 'work',
        name: 'work',
        component: Workbench,
        meta: {
          title: "工作台",
          imgIndex: 1
        }
      },
      {
        path: 'new',
        name: 'new',
        component: Newvisit,
        meta: {
          title: "新开就诊",
          imgIndex: 2
        }
      },
      {
        path: 'register',
        name: 'register',
        component: Register,
        meta: {
          title: "挂号管理",
          imgIndex: 3
        }
      },
      {
        path: 'drug',
        name: 'drug',
        component: Drug,
        meta: {
          title: "药品零售",
          imgIndex: 0
        }
      },
      // {
      //   path: 'charge',
      //   name: 'charge',
      //   component: Charge,
      //   meta: {
      //     title: "收费管理",
      //     imgIndex: 1
      //   }
      // },
      // {
      //   path: 'patient',
      //   name: 'patient',
      //   component: Patient,
      //   meta: {
      //     title: "患者管理",
      //     imgIndex: 2
      //   }
      // },
      // {
      //   path: 'drugmanagement',
      //   name: 'drugmanagement',
      //   component: Drugmanagement,
      //   meta: {
      //     title: "药品管理",
      //     imgIndex: 3
      //   }
      // },
      {
        path: 'case',
        name: 'case',
        component: Case,
        meta: {
          title: "病例管理",
          imgIndex: 1
        }
      },
    ]
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue')
  },

]

const router = new VueRouter({
  routes
})

import { getToken } from '../utils/cookieUtil.js';
import { GetUserDataByToken } from '../api/LoginApi.js';
import store from '../store';
let whiteAr = ['/login/login', '/login/regist', '/login/findpwd', '/login/apply'];//白名单

var limitRoutes = [
  {
    path: 'member',
    name: 'member',
    component: Member,
    meta: {
      title: "会员管理", role: ["admin"],
      imgIndex: 2
    }
  },
  {
    path: 'statistics',
    name: 'statistics',
    component: Statistics,
    meta: {
      title: "统计报表", role: ["admin"],
      imgIndex: 3
    }
  }
]
function GetPermissionRoutes(role, arr) {
  var ret = [];
  arr.forEach(item => {
    if (item.meta.role.includes(role)) {
      ret.push(item);
    }
  });
  return ret;
}

router.beforeEach((to, from, next) => {
  // console.log("当前要跳转的界面是：",to);
  //首先判断用户是否登录了
  var token = getToken("token");
  var path = to.path;
  if (token)//登录
  {
    // console.log("登录了");
    if (path == '/login/login') {
      next('/');
    } else {
      if (store.state.routes.length == 0) {
        GetUserDataByToken({ token }).then(res => {
          console.log("获取用户:", res);
          if (res.code == 200) {
            var user = res.data;
            store.commit("SetUser", user);
            // 通过用户权限获取路由数组
            var newRoutes = GetPermissionRoutes(user.role, limitRoutes);
            console.log("当前用户：", user, "获取的权限是:", user.role);
            // console.log("当前路由newRoutes：", newRoutes);
            routes[2].children = routes[2].children.concat(newRoutes);
            // console.log("当前路由：", routes[2].children);
            store.commit("SetRoutes", routes);
            router.addRoutes(routes);
            next({ ...to, replace: true });
          }
        });
      } else {
        // console.log("当前已经获取过数据");
        next();
      }
    }
  }
  else//未登录
  {
    if (whiteAr.includes(path))//在白名单中
    {
      // console.log("白名单？")
      next();
    } else {//不在白名单 强行跳转到登录界面登录
      // console.log("跳到登录")
      next("/login/login")
    }
  }
  // next();
})

// 该段代码不需要记，理解即可
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

export default router
